<!DOCTYPE html>
<html ng-app="customControl">
<head>
  <title>asyncValidators</title>
  <meta charset="utf-8">
  <link rel="stylesheet" href="http://cdn.bootcss.com/bootstrap/3.3.2/css/bootstrap.css">
  <style>
    *{font-family: 'MICROSOFT YAHEI'}
  </style>
</head>
<body>
<div class="container" ng-controller="ctrl">
  <div ng-include="'../../common/header.html'"></div>
  <div class="page-header">
    <h1>ngModelController- <small>asyncValidators实现异步验证表单</small></h1>
  </div>
  <form role="form" name="myForm">
    <div class="form-group">
      <input validate-name type="text" name="myWidget" ng-model="userContent" ng-model-options="{updateOn:'blur'}" class="form-control" required>
    </div>
    <div class="alert alert-danger" role="alert" ng-show="myForm.myWidget.$error.required">
      <strong>Oh!</strong> 必填!
    </div>
    <div class="alert alert-danger" role="alert" ng-show="myForm.myWidget.$error.validCharacters">
      <strong>Oh!</strong> 不符合自定义的验证规则!
    </div>
    <div class="alert alert-danger" role="alert" ng-show="myForm.myWidget.$error.uniqueUsername">
      <strong>Oh!</strong> 已经存在的用户名!
    </div>
  </form>
  <div class="panel panel-primary">
    <div class="panel-heading">
      <h3 class="panel-title">用户名:</h3>
    </div>
    <div class="panel-body">
      {{userContent}}
    </div>
  </div>
  <div class="panel panel-primary">
    <div class="panel-heading">
      <h3 class="panel-title">正在异步验证中:</h3>
    </div>
    <div class="panel-body">
      {{myForm.myWidget.$pending}}
    </div>
  </div>
</div>

</body>
</html>
<script src="http://cdn.bootcss.com/angular.js/1.3.8/angular.js" type="text/javascript"></script>
<script>

  var app = angular.module('customControl',[]);
  app.controller('ctrl',function($scope){
  });

  app.directive('validateName',function($http,$q){
    return {
      restrict:'A',
      require:'?^ngModel',
      link:function(scope,iele,iattr,ctrl){
        ctrl.$validators.validCharacters = function(modelValue, viewValue) {
          var value = modelValue || viewValue;
          return value ? value.indexOf('bunny')!==-1 : true
        };
        ctrl.$asyncValidators.uniqueUsername = function(modelValue, viewValue) {
          var value = modelValue || viewValue;
          // Lookup user by username
          return $http.get('/api/users/' + value).
          then(function resolved(res) {
            if(res.data){
              //用户名已经存在,验证失败,给下一个promise传递失败通知.
              return $q.reject('res.data');
            }
            else {
              //用户名不存在,验证成功.
              return true
            }

          }, function rejected() {
            //username does not exist, therefore this validation passes
            //return true;
          })
        };
      }
    }
  });
</script>